import { login, logout, weixinComponentUserInfoCallback } from '@/api/account'
import { getToken, setToken, clearToken } from '@/utils/auth/token'
import { setCookieValue } from '@/utils/utils'
import { appConsts } from '@/utils/app-consts'
import abp from 'abp'

const state = {
  token: getToken()
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { rememberMe, username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, rememberMe: rememberMe }).then(result => {
        const { token } = result
        const tokenExpireDate = rememberMe ? (new Date(new Date().getTime() + 1000 * 1000)) : undefined
        commit('SET_TOKEN', token)
        setToken(token, tokenExpireDate)
        setCookieValue(appConsts.authorization.encrptedAuthTokenName, token, tokenExpireDate, abp.appPath)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  weixinComponentLogin({ commit }, data) {
    return new Promise((resolve, reject) => {
      weixinComponentUserInfoCallback(data).then(result => {
          const rememberMe = true;
          const tokenExpireDate = rememberMe ? (new Date(new Date().getTime() + 1000 * 10000000)) : undefined
          commit('SET_TOKEN', result)
          setToken(result, tokenExpireDate)
          setCookieValue(appConsts.authorization.encrptedAuthTokenName, result, tokenExpireDate, abp.appPath)
          resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    debugger
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        clearToken()
        // resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      clearToken()
      resolve()
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
